package org.luxor.commons.mqtt.listener;

import cn.hutool.json.JSONUtil;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.luxor.commons.core.web.data.R;
import org.luxor.commons.mqtt.annotation.MqttTopicListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * 接收任务执行指令
 *
 * @author Mr.yan @date 2023/12/18
 */
@Component
@MqttTopicListener("dispatcher/${spring.mqtt.client-id:1}/task/#")
public class ReceiveTaskCmd implements IMqttMessageListener {

    @Resource
    private MqttClient mqttClient;

    @Value("${spring.mqtt.client-id:1}")
    private String clientId;

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String request = new String(message.getPayload(), StandardCharsets.UTF_8);
        System.out.println("[Server] 接受任务:" + topic + " 内容:" + request);

        String taskName = topic.substring(topic.lastIndexOf("/task/") + 6);
        String pubTopic = "receive/" + clientId + "/task/" + taskName;
        R<String> response = R.ok("处理成功");
        MqttMessage result = new MqttMessage(JSONUtil.toJsonStr(response).getBytes(StandardCharsets.UTF_8));
        result.setId(message.getId());
        result.setRetained(false);
        result.setQos(2);
        mqttClient.publish(pubTopic, result);
        System.out.println("[Server] 响应结果:" + pubTopic + " 内容:" + JSONUtil.toJsonStr(response));
    }

}
